/**
 * ===========================================================================
 * 版权所有 湖南免了么网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.mianle.me
 * ===========================================================================
 * 21:36 2018/7/3
 */
package com.mianle.userapi.service;

import com.mianle.userapi.mapper.GaodeMapper;
import com.mianle.userapi.mapper.WalletAccountLogMapper;
import com.mianle.userapi.mapper.WalletUserMapper;
import com.mianle.userapi.model.Gaode;
import com.mianle.userapi.model.WalletAccountLog;
import com.mianle.userapi.model.WalletUser;
import com.mianle.userapi.util.BigNum;
import com.mianle.userapi.util.Tools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author: yiyuan
 * @Description:
 * @Date: Created in 21:36 2018/7/3
 *
 */
@Slf4j
@Service
public class TestException {

    @Autowired
    private GaodeMapper gaodeMapper;

    @Autowired
    private TestException testException;

    public int test1() {
        Gaode gao = new Gaode();
        gao.setAddrName("TestException");
        gao.setLatitude(65.5656);
        gao.setLongitude(89.25656);
        int r = gaodeMapper.save(gao);
        return r;
    }

    @Transactional(rollbackFor = Exception.class)
    public int test2()  {
        int  r= 0;
        try {
            Gaode gao = new Gaode();
            gao.setAddrName("TestException");
            gao.setLatitude(65.5656);
            gao.setLongitude(89.25656);
            r = gaodeMapper.save(gao);
            if(r > 0) {
                r = 12 / 0;
            }
            return r;
        } catch (Exception eexception) {
            throw eexception;
            //eexception.printStackTrace();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public int test3()  {
        int  r= 0;
        Gaode gao = new Gaode();
        gao.setAddrName("TestException");
        gao.setLatitude(65.5656);
        gao.setLongitude(89.25656);
        r = gaodeMapper.save(gao);
        if(r > 0) {
            System.out.println("--------------插入成功----------------------");
            Gaode gao1 = new Gaode();
            gao1.setAddrName("Test001");
            gao1.setLatitude(65.5656);
            gao1.setLongitude(89.25656);
            int r1 = gaodeMapper.save(gao1);
            //假设没有保存成功
            r1 = 0;
            if(r1 == 0) {
                System.out.println("--------------假设没有保存成功----------------------");
                r = r1;
                throw new RuntimeException();
                //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                //return r1;
            }
        }
        return r;
    }


    @Autowired
    private WalletUserMapper walletUserMapper;


    @Autowired
    private WalletAccountLogMapper walletAccountLogMapper;

    @Autowired
    private TestException2 testException2;


    @Transactional(rollbackFor = Exception.class)
    public void test4()  {
        log.info("-----------积分返余额-------------");
        //比例
        BigDecimal pointsToBalance = NumberUtils.createBigDecimal(String.valueOf(0.04));

        List<WalletUser> list = walletUserMapper.getList();
        WalletUser systemUser = new WalletUser();
        systemUser.setId(1L);
        for (WalletUser walletUser : list) {
            //系统账户不参与积分返余额
            if(walletUser.getId() == 1) {
                log.info("----------系统账户 {} 不参与积分返余额---------", walletUser.getId());
                continue;
            }
            //用户积分
            Float basePoint = walletUser.getBasePoint();
            if (basePoint == null || basePoint <= 0) {
                log.info("---------- 用户 {} 积分为 {} 不参与积分返余额-----------", walletUser.getId(), basePoint);
                continue;
            }
            //获取系统账户
            WalletUser walletUserSystem = (WalletUser)walletUserMapper.selectOne(systemUser);
            Float sysBce = walletUserSystem.getBalance();
            //系统余额为NULL或0
            if(sysBce == null || sysBce <= 0) {
                log.info(" ------- 系统余额为 {} ---------", sysBce);
                continue;
            }
            //积分返余额
            BigDecimal rebate = NumberUtils.createBigDecimal(String.valueOf(basePoint)).multiply(pointsToBalance);
            int compareVal = rebate.compareTo(new BigDecimal(0.01));
            //判断用户积分换余额
            if (compareVal < 0) {
                log.info("----------- 积分返余额少于0.01, 不参与积分返余额 {},  ----------", rebate);
                continue;
            }

            testException.saveAccoutLog(rebate, walletUser, walletUserSystem);
            //testException2.saveAccoutLog(rebate, walletUser, walletUserSystem);
        }
    }


    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void saveAccoutLog(BigDecimal rebate, WalletUser walletUser, WalletUser walletUserSystem) {
            //更新用户
            int result = walletUserMapper.releaseUserBace(rebate, walletUser.getId());
            if(result <= 0) {
                saveException(walletUser);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }


            //日志-用户账户加余额
            WalletAccountLog userAddLog = new WalletAccountLog();
            userAddLog.setUserId(walletUser.getId());
            userAddLog.setChangeType(100);
            userAddLog.setChangeTime(Tools.getCurUnixTime());
            userAddLog.setChangeDesc("换");
            userAddLog.setCurrData(rebate.abs());
            userAddLog.setTotalData(BigNum.add(new BigDecimal(walletUser.getBalance()), rebate));
            userAddLog.setToUserId(walletUserSystem.getId());
            result = walletAccountLogMapper.save(userAddLog);
            if(result <= 0) {
                saveException(walletUser);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            //日志-用户账户减积分
            WalletAccountLog userSubtractLog = new WalletAccountLog();
            userSubtractLog.setUserId(walletUser.getId());
            userSubtractLog.setChangeType(101);
            userSubtractLog.setChangeTime(Tools.getCurUnixTime());
            userSubtractLog.setChangeDesc("换");
            userSubtractLog.setCurrData(rebate.negate());
            userSubtractLog.setTotalData(new BigDecimal(walletUser.getBasePoint()).subtract(rebate));
            userSubtractLog.setToUserId(walletUserSystem.getId());
            result = walletAccountLogMapper.save(userSubtractLog);
            if(result <= 0) {
                saveException(walletUser);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            if (String.valueOf(walletUser.getId()).equals("3")) {
                saveException(walletUser);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            //更新系统用户
            result = walletUserMapper.releaseSysBace(rebate, walletUserSystem.getId());
            if(result <= 0) {
                saveException(walletUser);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            //日志-系统账户减余额
            WalletAccountLog systemAddLog = new WalletAccountLog();
            systemAddLog.setUserId(walletUserSystem.getId());
            systemAddLog.setChangeType(100);
            systemAddLog.setChangeTime(Tools.getCurUnixTime());
            systemAddLog.setChangeDesc("换");
            systemAddLog.setCurrData(rebate.negate());
            systemAddLog.setTotalData(BigNum.subtract(new BigDecimal(walletUserSystem.getBalance()), rebate));
            systemAddLog.setIp("127.0.0.1");
            systemAddLog.setToUserId(walletUser.getId());
            result = walletAccountLogMapper.save(systemAddLog);
            if(result <= 0) {
                saveException(walletUser);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            //日志-系统账户加积分
            WalletAccountLog systemSubtractLog = new WalletAccountLog();
            systemSubtractLog.setUserId(walletUserSystem.getId());
            systemSubtractLog.setChangeType(101);
            systemSubtractLog.setChangeTime(Tools.getCurUnixTime());
            systemSubtractLog.setChangeDesc("换");
            systemSubtractLog.setCurrData(rebate.abs());
            systemSubtractLog.setTotalData(new BigDecimal(walletUserSystem.getBasePoint()).add(rebate));
            systemSubtractLog.setIp("127.0.0.1");
            systemSubtractLog.setToUserId(walletUser.getId());
            result = walletAccountLogMapper.save(systemSubtractLog);
            if(result <= 0) {
                saveException(walletUser);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }


    }

    public void saveException(WalletUser walletUser) {
        System.out.println("-------------------积分返余额----------用户---"+walletUser.getMobilePhone()+"---出现错误,需手共处理");
    }


    public static void main(String[] args) {
        String cron = "0 5 0 * * ? ";
        System.out.println(cron.trim());
    }
}
